package com.atung.merchant.config.security;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 流量管控
 *
 * @author Administrator
 */
@Component
public class FlowConfiguration {
    public static long seconds = 5L;
    //初始化桶大小
    public static Long minInitialize = 1L;
    public static Long maxInitialize = 10L;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Boolean currentLimiting(String ip, String url) {
        if (stringRedisTemplate.hasKey(url + ip)) {
            //获取当前访问次数（进行原子加+）
            Long increment = stringRedisTemplate.boundValueOps(url + ip).increment(1);
            //验证是否开启ip禁用
            if (increment > maxInitialize) {
                stringRedisTemplate.opsForValue().set(url + ip, String.valueOf(increment), seconds, TimeUnit.SECONDS);
                return false;
            }

        } else {
            stringRedisTemplate.opsForValue().set(url + ip, String.valueOf(minInitialize), seconds, TimeUnit.SECONDS);
        }
        return true;
    }
}
